// -----------------------------------------------------------------------
//  <copyright file="SetPasswordCommand.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2025 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-03-04 23:03</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Identity.Domain.Entities;

using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;


namespace DaprPlus.Identity.Application.Identity.Users.Commands;

[AuthConfig(typeof(User), ResourceAccessType.RoleLimit, "SetPassword")]
public class SetPasswordCommand : IRequest<ApiResult>, ICommand
{
    public long UserId { get; set; }

    public required string Password { get; set; }

    public required string ConfirmPassword { get; set; }
}

public class SetPasswordCommandHandler(IServiceProvider provider) : IRequestHandler<SetPasswordCommand, ApiResult>
{
    public async Task<ApiResult> Handle(SetPasswordCommand request, CancellationToken cancellationToken)
    {
        var userManager = provider.GetRequiredService<UserManager<User>>();

        // 查找用户
        var user = await userManager.FindByIdAsync(request.UserId.ToString());
        if (user == null)
        {
            return new ApiResult(ApiResultType.Error, $"用户ID为 {request.UserId} 的用户不存在");
        }

        // 检查用户是否已经设置了密码
        var hasPassword = await userManager.HasPasswordAsync(user);

        IdentityResult result;
        if (hasPassword)
        {
            // 如果用户已经有密码，则需要重置密码
            var token = await userManager.GeneratePasswordResetTokenAsync(user);
            result = await userManager.ResetPasswordAsync(user, token, request.Password);
        }
        else
        {
            // 如果用户没有密码，则添加密码
            result = await userManager.AddPasswordAsync(user, request.Password);
        }

        if (!result.Succeeded)
        {
            return new ApiResult(ApiResultType.Error, result.Errors.First().Description);
        }

        return new ApiResult(ApiResultType.Success, "密码设置成功");
    }
}

public class SetPasswordCommandValidator : AbstractValidator<SetPasswordCommand>
{
    public SetPasswordCommandValidator()
    {
        RuleFor(x => x.UserId).GreaterThan(0).WithMessage("用户ID必须大于0");

        RuleFor(x => x.Password)
            .NotEmpty().WithMessage("密码不能为空")
            .MinimumLength(6).WithMessage("密码长度不能少于6个字符");

        RuleFor(x => x.ConfirmPassword)
            .NotEmpty().WithMessage("确认密码不能为空")
            .Equal(x => x.Password).WithMessage("两次输入的密码不一致");
    }
}

